<template>
  <canvas id="canvas" ref="canvas" :width="width" :height="height"></canvas>
</template>
<script lang="ts">
import SourceModel from '@/game/model/SourceModel'
import cjs=createjs
import { loadManifestAsync, stageInit } from '@/utils/CreateJSHelper'
import { defineComponent, onMounted, onUnmounted, ref } from 'vue'
import { sr } from 'element-plus/es/locale'
import { watch } from 'vue'
class AnimationRoot extends cjs.Container {
  constructor(data:SourceModel){
    super()
    console.log(data)
    this.addChild(this.createAnimation(data))
  }
  setData(src:SourceModel){
    this.removeAllChildren()
    this.addChild(this.createAnimation(src))
  }
  private createAnimation(src:SourceModel):cjs.Sprite{
    const images=this.getUrls(src)
    const frames=this.getFrames(src)
    const data={
      images: images,
      frames: frames
    }
    console.log(data)
    const spriteSheet=new cjs.SpriteSheet(data)
    //spriteSheet.framerate=10
    const sp=new cjs.Sprite(spriteSheet)
    //sp.framerate=10
    sp.play()
    return sp
  }
  private getUrls(src:SourceModel):string[]{
    const arr:string[]=[]
    let mod=''
    for(let i=0;i<src.digits;i++){
      mod+='0'
    }
    for(let i=src.start;i<=src.end;i++){
      const name=mod+i
      arr.push(process.env.VUE_APP_BASE_API+src.path+name.substring(name.length-src.digits)+src.ext)
    }
    return arr
  }
  private getFrames(src:SourceModel):number[]{
    const frames=[]
    let j=0
    for(let i=src.start;i<=src.end;i++){
      frames.push([src.originx,src.originy,src.width,src.height,j])
      j++
    }
    return frames
  }
}
export default defineComponent({
  name: 'SpriteAnimation',
  props:{
    data:SourceModel,
    width:{
      type:Number,
      default:800
    },
    height:{
      type:Number,
      default:600
    }
  },
  setup(props, ctx) {
    //const baseUrl=process.env.VUE_APP_BASE_API
    const canvas=ref()
    
    onMounted(()=>{
      const stage=stageInit(canvas.value)
      const root=new AnimationRoot(props.data)
      stage.addChild(root)
      watch(props.data,(n,o)=>{
        root.setData(n)
      })
    })
    return {
      canvas
    }
  }
})
</script>